<template>
  <div style="width: 100%;height: 100vh; background-color: dodgerblue; overflow: hidden"> <!--overflow: hidden去掉边距-->
    <div style="width: 400px; margin: 150px auto"> <!--auto表示居中-->
      <div style="color: #cccccc; font-size: 30px; text-align: center; padding: 30px">欢迎登录</div>
      <el-form ref="form" :model="form" size="mormal" :rules="rules">
        <el-form-item prop="username">
          <el-input :prefix-icon="UserFilled" v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" :prefix-icon="lock" v-model="form.password" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button v-if="isLogin" style="width: 100%" type="primary" @click="login">登录</el-button>
        </el-form-item>
        <el-form-item>
          <el-button v-if="isLogin" style="width: 100%" type="primary" @click="register">注册</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import {UserFilled} from "@element-plus/icons";
import lock from "@element-plus/icons/lib/Lock";
import request from "@/utils/request";
import register from "@/views/Register.vue";

export default {
  name: "Login",
  computed: {

    lock() {
      return lock
    },
    UserFilled() {
      return UserFilled
    }
  },
  data() {
    return {
      form: {},
      user:{},
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
        ]
      },
      isLogin:true
    }
  },

  methods:{
       login(){
      this.$refs['form'].validate((valid) => { // 验证请求，只有在输入了账号密码才能发送请求
        // form要与el-form ref="form"命名的名字一样
        if (valid) {
          request.post("/user/login" , this.form).then(res=>{
            console.log(res)
            if (res.code === '200') {
              this.$message({
                type: "success",
                message: "登录成功"
              })
              sessionStorage.setItem("user",JSON.stringify(res.data)) // 获取用户信息
              this.$router.push("/") // 登录成功后页面跳转到首页
            } else {
              this.$message({
                type: "error",
                message: res.msg
              })
            }
          })
        }
      })

    },
    register(){
      this.$router.push("/register")
    }
  }
}
</script>


<style scoped>

</style>